// pages/pay/pay.js
const app = getApp()
const WXAPI = require("../../api/api")
Page({
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '确认付款', // 导航栏 中间的标题
      textColor: '#333', // 标题颜色
      bgColor: '#fff', // 导航栏背景颜色
      isloading: true,
      isColor: true,
    },
    nvabarDataSu: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '确认付款', // 导航栏 中间的标题
      textColor: '#333', // 标题颜色
      bgColor: '#fff', // 导航栏背景颜色
      backUrl: '/pages/userMarket/userMarket'
    },
    //创建订单需要的参数
    payClient: "1", //支付客户端 1 微信 2 支付宝
    merchantId: '', //商户id
    amount: '', //输入金额
    payAmount: '0.00', //实际支付金额
    walletIds: [], //钱包id数组（使用积分抵扣时传）
    cardPayMoney: 0, //卡支付金额
    cardId: '', //选择卡ID
    remark: '', //备注
    payScene: '', //支付场景(微信支付时必传) 1 扫码支付 2 直接购买
    assetId: '', //资产id（用户从消费页面进来携带）
    useWalletInfos: [],
    code: '',
    giveMoney: 0, //赠送金额


    //页面其他参数
    
    _options: {},
    
    imgHttp: app.globalData.imgHttp, //图片前缀
    qrCodeUrl: '',
    pageData: {}, //支付页面信息
    cardData: {}, //选中卡后传过来的值
    cardList: [],
    selCardMoney: 0,//选择用卡后需要支付的金额
    isHasCard: '', //是否可以选可用卡
    
    cardShow: false, //卡弹窗
    selCard: false,//是否勾选卡
    discountMoney: 0, //折扣金额
    totalPrice: 0,//总价
    appid: app.globalData.appid,
    phone: '',
    payShow: false, //可以点击确定支付创建订单
    payKong: false, //商家没有入驻
    selected: true, //
    anonymity: '2', //1 匿名用户 2 非匿名用户
    isWx: '', //微信扫码进来
    countdown: 60,
    orderId: '',
    cardBalance: 0,//卡内余额
    ismaidian: false,
    deleteToken: false,
    orderManageId: '', //去掉订单id
    keyCodeShow: false,
    wxUrl: '',

    //优惠券参数
    receiveShow: false,
    myVouchersShow: false,
    tagList: [],
    isHasVou: '',//是否可以选用券
    vouTotal: 0, //券总量
    vouData: {},//选择券的信息
    isSelVouchers: false,//是否选择了券
    preferentialMoney: 0,//优惠券优惠金额
    customerCouponId: '', //客户优惠券id（优惠券抵扣时传） 
  },
  onLoad: function (options) {
    
    this.setData({
      _options: options,
      mobbleBottom: app.mobile.mobbleBottom,
     
    })
    var isWx = options.isWx
    
    this.setData({
      isWx: isWx,
    })
    this.dialog = this.selectComponent("#auth_dialog");
    var token = wx.getStorageSync('token')
    console.log("哈哈哈啊哈哈啊哈", token)
    if (token == '') {
      this.login('no')
      // this.dialog.showPhone()
      return false
    }
    console.log("拒绝授权")
    //微信客户端扫码支付
    var wxUrl = decodeURIComponent(options.q)
    if (wxUrl && wxUrl != 'undefined') {
      var num = wxUrl.indexOf("?")
      wxUrl = wxUrl.substring(num + 1); //
      wxUrl = wxUrl.split("code=");
      wxUrl = wxUrl[1]
      wxUrl = JSON.parse(wxUrl)
      console.log("微信扫二维码支付", )
      this.setData({
        qrCodeUrl: wxUrl.param,
        payScene: 1,
        isWx: true,
      })
      this.getParCollectionQrCodeUrl()
    }
    //蜜链盟券立即消费进入
    var scanUrl = options.scanUrl
    var assetId = options.assetId
    
    var merchantId = options.merchantId
    // var merchantId = '1427896779155771394'    1542774232377790466
    if (merchantId) {
      this.setData({
        merchantId: merchantId,
        assetId: assetId,
        payScene: 2,
      })
      this.getConfirmInfo()
      if(this.data.anonymity == 2){
        this.getCard()
        this.getTag()
        this.getVoucher()
      }
    }
    //蜜链盟用户端扫码进入
    // var QRmerchantId = '1384317372986413058'
    var QRmerchantId = options.QRmerchantId
    var staffId = options.staffId != 'undefined' ? options.staffId :'';
    if (QRmerchantId) {
      console.log("扫二维码支付")
      this.setData({
        merchantId: QRmerchantId,
        payScene: 1,
        staffId: staffId,
      })
      this.getConfirmInfo()
      if(this.data.anonymity == 2){
        this.getCard()
        this.getTag()
        this.getVoucher()
      }
      
    }
    this.setNavSize()
  },
  //解析二维码confirmInfo
  getParCollectionQrCodeUrl() {
    const that = this
    var data = {
      qrCodeUrl: this.data.qrCodeUrl,
      // qrCodeUrl:'https://bee.xiaodaiyan.com/pay/uQRxY%2F6Y4pbfVN4%2BbISi5WEG2fcys%2Beg9h2%2B0dfXuU8%3D',  
    }
    WXAPI.parCollectionQrCodeUrl(data, (res) => {
      const data = res.result
      console.log("解析二维码", res)
      if (res.code === 200) {
        this.setData({
          merchantId: data.merchantId,
        })
        this.getConfirmInfo()
        if(this.data.anonymity == 2){
          this.getCard()
          this.getTag()
          this.getVoucher()
        }
       
      } else {
        this.setData({
          payKong: true
        })
      }
    })
  },
  //支付页面信息
  getConfirmInfo() {
    const that = this
    var data = {
      merchantId: this.data.merchantId,
    }
    WXAPI.confirmInfo(data, (res) => {
      const data = res.result
      console.log("支付页面信息", res)
      if (res.code === 200) {
        this.setData({
          pageData: res.result,
        })
      }

    })
  },
  //初始化参数
  init(){
    var amount = this.data.amount
    this.setData({
      payAmount: amount,
      totalPrice: amount,//总价
      walletIds: [],//折扣
      selCard: false,//不勾选卡
      cardId: '',//选择卡ID
      discountMoney: 0,//折扣金额
      cardData: {}, //清空选中的卡数据
      cardPayMoney: 0, //卡支付金额清零
      giveMoney: 0, //赠送金额
      cardBalance: 0,//卡支付金额90u.,              
    })
  },
  //获取卡
  getCard() {
    var data = {
      merchantId: this.data.merchantId
    }
    WXAPI.cardPayDetail(data, (res) => {
      var isHasCard = ''
      if (res.result.appCustomerCardPayDTOList.length > 0) {
        isHasCard = true
      } else {
        isHasCard = false
      }
      this.setData({
        cardList: res.result.appCustomerCardPayDTOList,//拥有的卡
        contractPath: res.result.contractPath,
        isHasCard: isHasCard,
      })
    })
  },
  getVoucher(){
    var data = {
      merchantId: this.data.merchantId
    }
    WXAPI.assetCount(data, (res) => {
      const {grouponOrderNum,shopCouponNum,wxGrouponOrderNum,total} = res.result
      var isHasVou = ''
      if(total > 0){
        isHasVou = true
      }else{
        isHasVou = false
      }
      this.setData({
        vouTotal: total,
        isHasVou: isHasVou,
      })
    })
  },
  //获取店铺标签
  getTag(){
    var data = {
      merchantId: this.data.merchantId
    }
    WXAPI.merchantTag(data, (res) => {
      this.setData({
        tagList: res.result,//拥有的卡
      })
    })
  },
  //卡弹窗
  handleCard() {
    this.setData({
      cardShow: true,
    })
  },
  //卡弹窗关闭
  handleChose() {
    this.setData({
      cardShow: false,
    })
  },
  //卡弹窗确认后传过来所选卡的信息
  handleConfirm(e) {
    console.log('e', e.detail)
    this.setData({
      cardData: e.detail,
      payAmount: this.data.TicketPayAmount,
      cardType: e.detail.cardType
    })
    this.initVouchers()//清空选择优惠券的信息
  },
  //是否选择了卡
  handleselCard(e) {
    console.log('e', e.detail)
    this.setData({
      selCard: e.detail
    })
    this.calculateCard()
  },
  //输入金额变化
  changeAmount(e) {
    var amount = this.PointNum(e.detail.value)
    var totalPrice = parseFloat(amount)
    console.log("钱变化",totalPrice)
    this.setData({
      amount: amount,
      totalPrice: Math.round(totalPrice * 100) / 100,
    })
    
    this.init()
  },
  //输入金额框获得焦点
  focusAmount(){
    console.log(1111111111)
    wx.hideKeyboard();
    this.setData({
      keyCodeShow: !this.data.keyCodeShow,
    })
  },
  handleChoseKey(){
    this.setData({
      keyCodeShow: false,
    })
  },
  //输入金额框失去焦点
  hangdleAmount() {
    console.log('失去焦点')
    var amount = this.data.amount
    var cardList = this.data.cardList
    // if (cardList.length == 1) {
    //   this.setData({
    //     cardData: cardList[0],
    //     selCard: true,
    //   })
    //   this.calculateCard()
    // }
    if(this.data.isSelVouchers){
      this.calculateVouchers()
    }
    
    this.setData({
      payShow: true,
    })
  },
  //选择卡后执行的计算
  calculateCard() {
    var payAmount = this.data.amount
    var balanceMoney = parseFloat(this.data.cardData.balanceMoney)
    var cardPayMoney = this.data.cardPayMoney //股东卡抵扣金额
    var selCardMoney = this.data.selCardMoney //选择卡后需要支付的金额
    var discountMoney = 0 //折扣金额
    var cardBalance = this.data.cardBalance//卡内余额
    if (this.data.cardData.discount) { //有折扣
      var discount = parseFloat(this.data.cardData.discount) / 10 //卡折扣
    } else { //没折扣
      var discount = 1 //卡折扣
    }
    console.log('折扣', discount)
    console.log('折扣', this.data.selCard)
    if (this.data.selCard) {
      if (balanceMoney > payAmount * discount) {
        cardPayMoney = payAmount * discount
        selCardMoney = 0
        discountMoney = discountMoney + (payAmount - payAmount * discount)
        cardBalance = balanceMoney - payAmount * discount//卡余额还剩多少
      } else if (balanceMoney <= payAmount * discount) {
        cardPayMoney = balanceMoney
        cardBalance = 0//卡余额还剩多少
        if (this.data.cardData.discount) {
          selCardMoney = Math.round(payAmount * discount * 100) / 100 - balanceMoney
          console.log('实际支付金额', selCardMoney)
        } else {
          selCardMoney = payAmount - balanceMoney
        }
        discountMoney = discountMoney + (payAmount - payAmount * discount)
      }
      cardPayMoney = this.roundFixed(cardPayMoney, 2)
      this.setData({
        payAmount: Math.round(selCardMoney * 100) / 100,
        cardPayMoney: cardPayMoney,
        discountMoney: Math.round(discountMoney * 100) / 100,
        cardId: this.data.cardData.id,
        cardBalance: Math.round(cardBalance * 100) / 100,
      })
    } else {
      console.log('无卡')
      var payAmount = this.data.amount
      this.setData({
        payAmount: payAmount,
        cardPayMoney: 0,
        discountMoney: discountMoney,
        cardId: '',
      })
    }
  },
  //选择券后的计算
  calculateVouchers(){
    var vouData = this.data.vouData
    var amount = this.data.amount//输入金额
    var payAmount = this.data.payAmount//实际支付金额 
    var preferentialMoney = this.data.preferentialMoney //优惠券优惠金额
    if(amount < vouData.preferentialCondition){
      var title = `很抱歉该优惠券[满${vouData.preferentialCondition}]可用,请先修改支付金额`
      // if(vouData.couponType == 1){
      //   var title = `很抱歉【满${vouData.preferentialCondition}减${vouData.preferentialDiscount}】优惠券无法在该店铺使用`
      // }else if(vouData.couponType == 2){
      //   var title = `很抱歉【满${vouData.preferentialCondition}打${vouData.preferentialDiscount}折】优惠券无法在该店铺使用`
      // }
      wx.showToast({
        title: title,
        icon: 'none',
      })
      this.initVouchers()
    }else{
      if(vouData.couponType == 1){
        payAmount = amount - vouData.preferentialDiscount
        this.setData({
          customerCouponId: vouData.id,
          preferentialMoney: vouData.preferentialDiscount,
          payAmount: Math.round(payAmount * 100) / 100,
        })
      }else if(vouData.couponType == 2){
        payAmount = amount * (vouData.preferentialDiscount/10)
        preferentialMoney = amount - payAmount
        this.setData({
          customerCouponId: vouData.id,
          preferentialMoney: Math.round(preferentialMoney * 100) / 100,
          payAmount: Math.round(payAmount * 100) / 100,
        })
      }
      
    }
  },
  //优惠券初始化
  initVouchers(){
    this.setData({
      preferentialMoney: 0,
      payAmount: this.data.amount,
      vouData: {},
      isSelVouchers: false,
      customerCouponId: '',//优惠券ID
    })
  },
  amountData(e){
    var amountData = e.detail
    if(amountData){
      this.setData({
        payShow: true,
      })
    }else{
      this.setData({
        payShow: false,
      })
    }
    this.setData({
      amount: amountData,
      payAmount: amountData,
      totalPrice: Math.round(amountData * 100) / 100,
    })
    console.log('amountData',amountData)
  },
  //勾选用户协议
  handleReading() {
    this.setData({
      selected: !this.data.selected
    })
  },
  //匿名支付获取token
  getToken() {
    var code = this.data.code
    console.log('code', code)
    var data = {
      code: code,
      appid: app.globalData.appid,
    }
    WXAPI.silentAuthorization(data, (res) => {
      const data = res.result
      console.log("获取token", res)
      if (res.code === 200) {
        wx.setStorageSync('token', data.token)
        wx.setStorageSync('phone', data.phone)
        this.setData({
          anonymity: data.anonymity,
        })
        this.onLoad(this.data._options)
      }
    })
  },
  login(type) {
    // 登录 
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
          console.log('res.code',res.code)
          if(type == 'no'){
            that.getToken()
          }
          console.log('获取code', that.data.code)
        } else {
          console.log('获取code失败', res.errMsg)
        }
      }
    })
  },
  //数字格式化
  PointNum(obj) {
    var $this = this;
    obj = obj.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj = obj.replace(/^\./g, ""); //验证第一个字符是数字
    obj = obj.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    return obj;
  },
  //数字格式化
  roundFixed(num, fixed) {
    var pos = num.toString().indexOf('.'),
      decimal_places = num.toString().length - pos - 1,
      _int = num * Math.pow(10, decimal_places),
      divisor_1 = Math.pow(10, decimal_places - fixed),
      divisor_2 = Math.pow(10, fixed);
    return Math.round(_int / divisor_1) / divisor_2;
  },
  //取消订单
  cancelOrder(e) {
    var that = this
    var data = {
      id: that.data.orderManageId
    }
    WXAPI.cancelOrder(data, (res) => {
      const data = res.result
      if (res.code === 200) {
        that.getCard()
      }
    })
  },
  //创建订单
  handlePay() {
    const that = this
    if (!this.data.selected ) {
      wx.showToast({
        title: '请勾选购卡合同',
        icon: 'none'
      })
      return false
    }else if(!this.data.amount){
      wx.showToast({
        title: '请输入金额',
        icon: 'none'
      })
      return false
    }

    var data = {
      payClient: this.data.payClient, //支付客户端 1 微信 2 支付宝   .
      merchantId: this.data.merchantId, //商户id  .
      amount: parseFloat(this.data.amount), //金额 .
      payAmount: this.data.payAmount, //实际支付金额 .
      customerCouponId: this.data.customerCouponId, //客户优惠券id（优惠券抵扣时传）  .
      cardMoney: this.data.cardPayMoney, // .
      cardId: this.data.cardId, //   卡ID .
      payScene: this.data.payScene, //支付场景(微信支付时必传) 1 扫码支付 2 直接购买 .
      staffId: this.data.staffId, //
      paySource: app.globalData.paySource, //支付来源
    }
    console.log("创建订单", data)
    WXAPI.createOrderNew(data, (res) => {
      wx.showLoading({
        title: '支付中...',
        mask: 'true',
      })
      const data = res.result
      console.log("创建订单", res)
      if (res.code === 200) {
        this.data.orderManageId = res.result.orderManageId
        if (data.orderType == 1) {
          if (data.client == 1) {
            //微信支付
            wx.requestPayment({
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': data.signType, //MD5
              'paySign': data.paySign,
              'success': function (res) {
                wx.hideLoading()
                console.log('支付成功', res)
                console.log(res)
                if (res.errMsg == 'requestPayment:ok') {
                  wx.showToast({
                    title: '支付成功',
                  })
                  that.setData({
                    orderId: data.orderId
                  })
                  that.getCardPayorder()
                }
              },
              'fail': function (res) {
                that.cancelOrder()
                wx.hideLoading({
                  success: (res) => {
                    wx.showToast({
                      title: '支付失败',
                      icon: 'none'
                    })
                  },
                })
                console.log('支付失败或取消支付', res)
                if(that.data.selCard && !that.data.isSelVouchers){
                  that.init()
                }
                
              },
              'complete': function (res) {
                console.log('支付完成', res)
              }
            })
          } else if (data.client == 2) {
            //支付宝
          }

        } else if (data.orderType == 2) {
          //0元订单
          wx.redirectTo({
            url: '/pages/pay/paySuccess/paySuccess?orderId=' + data.orderId+'&anonymity=' + that.data.anonymity +'&deleteToken='+ that.data.deleteToken,
          })
        }
      }else{
        wx.hideLoading()
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }


    })
  },
  //购卡订单支付结果
  getCardPayorder() {
    const that = this
    console.log("that.data.anonymit", that.data.anonymit)
    this.setData({
      timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
        that.data.countdown--;
        var data = {
          orderId: that.data.orderId,
        }
        WXAPI.payResult(data, (res) => {
          const data = res.result
          console.log("获取支付结果", data.isPay)
         
          if (data.isPay) {
            wx.redirectTo({
              url: '/pages/pay/paySuccess/paySuccess?orderId=' + that.data.orderId + '&anonymity=' + that.data.anonymity +'&deleteToken='+ that.data.deleteToken,
            })
            clearInterval(that.data.timer);
          }
        })
        that.setData({
          countdown: that.data.countdown,
        })
        if (that.data.countdown == 0) {
          clearInterval(that.data.timer);
          that.setData({
            countdown: 60,
          })
        }
      }, 1000)
    })

  },
  // 通过获取系统信息计算导航栏高度
  setNavSize: function() {
    var that = this
        , sysinfo = wx.getSystemInfoSync()
        , statusHeight = sysinfo.statusBarHeight
        , isiOS = sysinfo.system.indexOf('iOS') > -1
        , navHeight;
    if (!isiOS) {
        navHeight = 48;
    } else {
        navHeight = 44;
    }
    console.log('statusHeight',statusHeight)
    console.log('navHeight',navHeight)
    that.data.top = statusHeight + navHeight
    that.setData({
        status: statusHeight,
        navHeight: navHeight
    })
  },
  //返回上一级
  handleBack(){
    if(this.data.anonymity == 1){
      wx.clearStorageSync()
      console.log('清空token',)
    }
    wx.navigateBack({
      delta: 1
    });
  },
  //关闭页面
  chosePage(){
    if(this.data.anonymity == 1){
      wx.clearStorageSync()
      console.log('清空token',)
    }
    wx.reLaunch({
      url: '/pages/userMarket/userMarket',
    })
  },
  //关闭店铺可用优惠券
  receiveChose(){
    this.setData({
      receiveShow: false,
    })
  },
  //打开店铺可用优惠券
  handleReceive(){
    this.setData({
      receiveShow: true,
    })
  },
  //关闭我的券包
  myVouchersChose(){
    this.setData({
      myVouchersShow: false,
    })
  },
  //打开我的券包
  handlePackage(){
    this.setData({
      myVouchersShow: true,
    })
  },
  //选择优惠券
  vouchersUse(e){
    console.log('选择了优惠券',e.detail)
    this.setData({
      vouData: e.detail
    })
    if(JSON.stringify(this.data.vouData) === '{}'){
      this.setData({
        isSelVouchers: false,
      })
    }else{
      this.init()
      this.setData({
        isSelVouchers: true,
      })
      this.calculateVouchers()
      
    }
    console.log('isSelVouchers',this.data.isSelVouchers)
  },
  handleLogin(){
    wx.clearStorageSync()
    if(this.data.anonymity == 1){
      this.login_dialog.loginShow()
    }
  },
  loginSuccess(){
    this.getTag()
    this.getCard()
    this.getVoucher()
    this.setData({
      anonymity: 2,
    })
  },
   /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.login_dialog = this.selectComponent("#login_dialog");
    var token = wx.getStorageSync('token')
    if(token){
      this.getVoucher()
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
})